package com.michael.ims.app.controller;

import com.michael.ims.app.QTblSystem;
import com.michael.ims.app.QTblUserToSystem;
import com.michael.ims.app.cache.SystemService;
import com.michael.ims.app.controller.io.system.DynamicRouteResp;
import com.michael.ims.app.controller.io.system.QuerySystemReq;
import com.michael.ims.app.controller.io.system.QuerySystemResp;
import com.michael.io.BaseUserInfoReq;
import com.michael.io.RespData;
import com.querydsl.core.types.Projections;
import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.SQLQueryFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Api("系统管理")
@RequestMapping("/system")
@RestController
public class SystemController {
    @Autowired
    private SQLQueryFactory sqlQueryFactory;

    @Autowired
    private SystemService systemService;

    @ApiOperation("查询该用户下具有访问权限的系统信息列表")
    @PostMapping("/query")
    @Transactional
    public RespData<List<QuerySystemResp>> query(@RequestBody @Valid QuerySystemReq req) {
        QTblUserToSystem tblUserToSystem = QTblUserToSystem.tblUserToSystem;
        QTblSystem tblSystem = QTblSystem.tblSystem;
        SQLQuery<QuerySystemResp> sqlQuery = sqlQueryFactory.select(Projections.bean(QuerySystemResp.class, tblSystem.name, tblSystem.picture, tblSystem.context))
                .from(tblSystem).join(tblUserToSystem)
                .where(tblSystem.id.eq(tblUserToSystem.systemId)
                        .and(tblUserToSystem.userId.eq(req.getUser().getId())));
        if (StringUtils.isNotBlank(req.getName())) {
            sqlQuery.where(tblSystem.name.contains(req.getName()));
        }
        List<QuerySystemResp> data = sqlQuery.fetch();
        return new RespData<>(data);
    }

    @ApiOperation("动态路由")
    @GetMapping("/dynamic-route")
    @Transactional
    public RespData<List<DynamicRouteResp>> dynamicRoute() {
        QTblSystem tblSystem = QTblSystem.tblSystem;
        List<DynamicRouteResp> data = systemService.list().stream().map(tuple -> {
            DynamicRouteResp dynamicRouteResp = new DynamicRouteResp();
            dynamicRouteResp.setContext(tuple.get(tblSystem.context));
            dynamicRouteResp.setId(tuple.get(tblSystem.id));
            dynamicRouteResp.setName(tuple.get(tblSystem.name));
            dynamicRouteResp.setUrl(tuple.get(tblSystem.url));
            return dynamicRouteResp;
        }).collect(Collectors.toList());
        return new RespData<>(data);
    }

}
